#!/bin/bash

# Redis Uninstall Script
# Function: Remove redis installation and related configurations
# Compatible: Anolis OS 7.9 and other Linux distributions
# Author: System Administrator
# Date: $(date +%Y-%m-%d)
#
# Usage Instructions:
# 1. Run with root privileges: sudo ./redis_uninstall.sh
# 2. Script will stop redis service, remove systemd service file,
#    and optionally remove installation directory and redis user

# set -e  # Don't exit on error for uninstall script

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Installation path
REDIS_INSTALL_DIR="/opt/RadMedical/product/tool/redis"

# Logging functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_question() {
    echo -e "${BLUE}[QUESTION]${NC} $1"
}

# Check if running as root user
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "This script requires root privileges to run"
        exit 1
    fi
}

# Show installation information
show_installation_info() {
    log_info "=========================================="
    log_info "redis Uninstall Script"
    log_info "=========================================="
    log_info "Installation path: $REDIS_INSTALL_DIR"
    log_info "Service file: /etc/systemd/system/redis.service"
    log_info "=========================================="
    echo ""
}

# Stop redis service
stop_redis_service() {
    log_info "Stopping redis service..."
    
    if systemctl is-active --quiet redis 2>/dev/null; then
        systemctl stop redis
        log_info "redis service stopped successfully"
    else
        log_warn "redis service is not running"
    fi
}

# Disable redis service
disable_redis_service() {
    log_info "Disabling redis service..."
    
    if systemctl is-enabled --quiet redis 2>/dev/null; then
        systemctl disable redis
        log_info "redis service disabled successfully"
    else
        log_warn "redis service is not enabled"
    fi
}

# Remove systemd service file
remove_systemd_service() {
    log_info "Removing systemd service file..."
    
    local service_file="/etc/systemd/system/redis.service"
    
    if [[ -f "$service_file" ]]; then
        rm -f "$service_file"
        log_info "Service file removed: $service_file"
        
        # Reload systemd daemon
        systemctl daemon-reload
        log_info "Systemd daemon reloaded"
    else
        log_warn "Service file not found: $service_file"
    fi
}

# Remove installation directory
remove_installation_directory() {
    log_info "Checking installation directory..."
    
    if [[ -d "$REDIS_INSTALL_DIR" ]]; then
        log_info "Found installation directory: $REDIS_INSTALL_DIR"
        
        read -p "Do you want to remove the installation directory? (y/N): " -n 1 -r
        echo
        
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            log_info "Removing installation directory..."
            rm -rf "$REDIS_INSTALL_DIR"
            log_info "Installation directory removed successfully"
        else
            log_warn "Installation directory kept: $REDIS_INSTALL_DIR"
        fi
    else
        log_warn "Installation directory not found: $REDIS_INSTALL_DIR"
    fi
}

# Remove redis user (optional)
remove_redis_user() {
    log_info "Checking redis user..."
    
    if id "redis" &>/dev/null; then
        log_info "redis user exists"
        
        read -p "Do you want to remove the redis user? (y/N): " -n 1 -r
        echo
        
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            log_info "Removing redis user..."
            userdel -r redis 2>/dev/null || userdel redis
            log_info "redis user removed successfully"
        else
            log_warn "redis user kept"
        fi
    else
        log_warn "redis user does not exist"
    fi
}

# Remove installed packages (optional)
remove_installed_packages() {
    log_info "Checking installed packages..."
    
    log_question "Do you want to remove the installed dependency packages?"
    log_info "  - gcc, make"
    read -p "Remove packages? (y/N): " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_warn "Removing installed packages may affect other software!"
        
        # Detect system type
        if [[ -f /etc/os-release ]]; then
            source /etc/os-release
            
            if [[ "$ID" == "anolis" ]] || [[ "$ID" == "centos" ]] || [[ "$ID" == "rhel" ]]; then
                log_info "Detected RedHat series system"
                log_info "Removing: gcc make"
                
                log_warn "Removing gcc and make may affect other software!"
                read -p "Continue? (y/N): " -n 1 -r
                echo
                
                if [[ $REPLY =~ ^[Yy]$ ]]; then
                    yum remove -y gcc make 2>&1 | grep -v "^$" || log_warn "Some packages may not be installed"
                else
                    log_info "Skipping package removal"
                fi
            elif [[ "$ID" == "ubuntu" ]] || [[ "$ID" == "debian" ]]; then
                log_info "Detected Debian series system"
                log_info "Removing: gcc make"
                
                log_warn "Removing gcc and make may affect other software!"
                read -p "Continue? (y/N): " -n 1 -r
                echo
                
                if [[ $REPLY =~ ^[Yy]$ ]]; then
                    apt-get remove -y gcc make 2>&1 | grep -v "^$" || log_warn "Some packages may not be installed"
                else
                    log_info "Skipping package removal"
                fi
            else
                log_warn "Unknown system type, skipping package removal"
            fi
            
            log_info "Package removal completed"
        else
            log_warn "Unable to detect system type for package removal"
        fi
    else
        log_info "Skipping package removal"
    fi
}

# Check if redis is running
check_redis_running() {
    if pgrep -f "$REDIS_INSTALL_DIR/bin/redis-server" >/dev/null; then
        log_warn "redis process is still running"
        log_warn "Attempting to stop it..."
        
        # Try to find the PID
        local pid=$(pgrep -f "$REDIS_INSTALL_DIR/bin/redis-server" | head -n1)
        if [[ -n "$pid" ]]; then
            kill -9 "$pid" 2>/dev/null && log_info "Stopped redis process (PID: $pid)"
        fi
    fi
}

# Verify uninstallation
verify_uninstallation() {
    log_info "Verifying uninstallation..."
    
    local issues_found=false
    
    # Check if service is still running
    if systemctl is-active --quiet redis 2>/dev/null; then
        log_error "redis service is still active"
        issues_found=true
    fi
    
    # Check if service file still exists
    if [[ -f /etc/systemd/system/redis.service ]]; then
        log_error "Service file still exists: /etc/systemd/system/redis.service"
        issues_found=true
    fi
    
    # Check if binary still exists
    if [[ -f "$REDIS_INSTALL_DIR/bin/redis-server" ]]; then
        log_warn "redis binary still exists: $REDIS_INSTALL_DIR/bin/redis-server"
    fi
    
    if [[ $issues_found == false ]]; then
        log_info "Uninstallation verification passed"
    else
        log_error "Uninstallation verification found some issues"
    fi
}

# Show completion message
show_completion_message() {
    log_info "=========================================="
    log_info "redis uninstallation completed!"
    log_info "=========================================="
    log_info ""
    log_info "Summary:"
    log_info "  ✓ redis service stopped"
    log_info "  ✓ redis service disabled"
    log_info "  ✓ systemd service file removed"
    log_info "  ✓ Installation directory (if confirmed)"
    log_info "  ✓ redis user (if confirmed)"
    log_info ""
    log_info "Note: If you need to reinstall redis, run the installation script again"
    log_info "=========================================="
}

# Main function
main() {
    log_info "Starting redis uninstallation..."
    
    # Check root privileges
    check_root
    
    # Show installation information
    show_installation_info
    
    # Confirmation
    log_warn "This script will:"
    log_warn "  1. Stop redis service"
    log_warn "  2. Disable redis service"
    log_warn "  3. Remove systemd service file"
    log_warn "  4. Optionally remove installation directory"
    log_warn "  5. Optionally remove redis user"
    log_warn "  6. Optionally remove dependency packages"
    echo ""
    
    read -p "Do you want to continue? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Uninstallation cancelled"
        exit 0
    fi
    
    # Stop redis service
    stop_redis_service
    
    # Additional check for running processes
    check_redis_running
    
    # Disable redis service
    disable_redis_service
    
    # Remove systemd service file
    remove_systemd_service
    
    # Remove installation directory
    remove_installation_directory
    
    # Remove redis user
    remove_redis_user
    
    # Optional: Remove installed packages
    echo ""
    remove_installed_packages
    
    # Verify uninstallation
    verify_uninstallation
    
    # Show completion message
    show_completion_message
    
    log_info "redis uninstallation script execution completed!"
}

# Execute main function
main "$@"

